<template>
  <!-- 搜索栏 -->
  <el-form inline :model="venueSearchModel">
    <el-form-item label="编号" prop="code">
      <el-input v-model="venueSearchModel.code" placeholder="请输入编号" style="width: 120px"></el-input>
    </el-form-item>
    <el-form-item label="名称" prop="name">
      <el-input v-model="venueSearchModel.name" placeholder="请输入名称" style="width: 120px"></el-input>
    </el-form-item>
    <el-form-item label="类型" prop="type">
      <el-select v-model="venueSearchModel.type" placeholder="请选择类型" style="width: 120px">
        <el-option label="足球场" value="足球场"></el-option>
        <el-option label="排球场" value="排球场"></el-option>
        <el-option label="羽毛球场" value="羽毛球场"></el-option>
        <el-option label="篮球场" value="篮球场"></el-option>
        <el-option label="乒乓球场" value="乒乓球场"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="开放时段" prop="openRange">
      <el-time-picker v-model="venueSearchModel.openRange"
                      range-separator="至"
                      placeholder="请选择时间范围"
                      is-range
                      format="HH:mm"
                      value-format="HH:mm:ss"
                      style="width: 180px"
        ></el-time-picker>
    </el-form-item>
    <el-form-item label="状态" prop="status">
      <el-select v-model="venueSearchModel.status" placeholder="请选择状态" style="width: 120px">
        <el-option label="启用" value="启用"></el-option>
        <el-option label="禁用" value="禁用"></el-option>
      </el-select>
    </el-form-item>
  </el-form>
  <!-- 操作栏 -->
  <div style="margin-bottom: 10px">
    <el-button type="primary" :icon="Plus" @click="add">新增</el-button>
    <el-button type="primary" :icon="Search" @click="search()">查询</el-button>
    <el-button type="primary" :icon="RefreshRight" @click="reset">重置</el-button>
    <el-button type="danger" :icon="Delete" @click="batchRemove">批量删除</el-button>
  </div>
  <!-- 内容栏 -->
  <el-table :data="venueModel" border stripe style="width: 100%" ref="tableRows" :row-class-name="getRowClass">
    <el-table-column type="selection" width="60" align="center"></el-table-column>
    <el-table-column label="ID" width="60" prop="id" align="center"></el-table-column>
    <el-table-column label="图标" width="60" align="center" prop="avatar">
      <template #default="scope">
        <el-avatar v-if="scope.row.avatar" :src="baseUrl + scope.row.avatar" size="small"></el-avatar>
        <el-icon v-else><picture-filled/></el-icon>
      </template>
    </el-table-column>
    <el-table-column label="编号" width="100" prop="code" align="center"></el-table-column>
    <el-table-column label="名称" width="120" prop="name" align="center"></el-table-column>
    <el-table-column label="类型" width="100" prop="type" align="center"></el-table-column>
    <el-table-column label="容量" width="80" prop="capacity" align="center">
      <template #default="scope">
        {{ scope.row.capacity }}人
      </template>
    </el-table-column>
    <el-table-column label="简介" width="220" prop="description" align="center"></el-table-column>
    <el-table-column label="位置" width="100" prop="location" align="center"></el-table-column>
    <el-table-column label="开启时间" width="120" prop="openTime" align="center"></el-table-column>
    <el-table-column label="关闭时间" width="120" prop="closeTime" align="center"></el-table-column>
    <el-table-column label="状态" width="80" prop="status" align="center"></el-table-column>
    <el-table-column label="操作" width="270" align="center" fixed="right">
      <template #default="scope">
        <el-button type="primary" size="small" :disabled="isDisable(scope.row.status)" @click="update(scope.row)">修改</el-button>
        <el-button type="danger" size="small" :disabled="isDisable(scope.row.status)" @click="toggleRowStatus(scope.row)">禁用</el-button>
        <el-button type="success" size="small" :disabled="isNormal(scope.row.status)"  @click="toggleRowStatus(scope.row)">解禁</el-button>
        <el-button type="danger" size="small" @click="remove([scope.row])">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页栏 -->
  <div style="display: flex; justify-content: center; margin-top: 10px">
    <el-pagination background
                   layout="prev, pager, next, total"
                   v-model:current-page="customerPage.pageNo"
                   v-model:page-size="customerPage.pageSize"
                   :total="customerPage.total"
                   @change="changePage"
                   style="text-align: center"/>
  </div>
  <!-- 新增/修改对话框 -->
  <el-dialog v-model="showDialog" :title="setTitle" width="500px" align-center>
    <el-form :model="venueFormModel" label-width="80px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="编号" prop="code">
            <el-input v-model="venueFormModel.code" placeholder="请输入编号"></el-input>
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input v-model="venueFormModel.name" placeholder="请选择名称"></el-input>
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-select v-model="venueFormModel.type" placeholder="请选择类型" style="width: 300px">
              <el-option label="足球场" value="足球场"></el-option>
              <el-option label="排球场" value="排球场"></el-option>
              <el-option label="羽毛球场" value="羽毛球场"></el-option>
              <el-option label="篮球场" value="篮球场"></el-option>
              <el-option label="乒乓球场" value="乒乓球场"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="图标" prop="avatar">
            <el-upload
                class="avatar-uploader"
                action="/api/admin/venue/upload/avatar"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :headers="headers">
              <el-avatar v-if="venueFormModel.avatar"
                         :src="baseUrl + venueFormModel.avatar" size="large"></el-avatar>
              <el-icon v-else class="avatar-uploader-icon">
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item label="开启时间" prop="openTime">
            <el-time-picker v-model="venueFormModel.openTime"
                            placeholder="请选择开启时间"
                            format="HH:mm"
                            value-format="HH:mm:ss"
            ></el-time-picker>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="状态" prop="status">
            <el-select v-model="venueFormModel.status" placeholder="请选择状态" style="width: 300px">
              <el-option label="启用" value="启用"></el-option>
              <el-option label="禁用" value="禁用"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item label="关闭时间" prop="closeTime">
            <el-time-picker v-model="venueFormModel.closeTime"
                            placeholder="请选择关闭时间"
                            format="HH:mm"
                            value-format="HH:mm:ss"
            ></el-time-picker>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="容量" prop="capacity">
            <el-input v-model="venueFormModel.capacity" placeholder="请输入容量" style="width: 300px"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="简介" prop="description">
        <el-input v-model="venueFormModel.description" placeholder="请输入简介" style="width: 310px"></el-input>
      </el-form-item>
      <el-form-item label="位置" prop="location">
        <el-input v-model="venueFormModel.location" placeholder="请输入位置" style="width: 310px"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="submitDialog()">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
:deep(.row-disable) {
  opacity: 0.4; /* 低亮度效果 */
}
.avatar-uploader {
  width: 120px; /* 正方形宽度 */
  height: 120px; /* 正方形高度（与宽度一致） */
  border: 1px dashed #d9d9d9;
  border-radius: 4px; /* 可选：轻微圆角 */
  cursor: pointer;
  display: flex; /* 启用flex布局 */
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
  overflow: hidden; /* 防止图片溢出容器 */
}

.avatar {
  width: 100%;
  height: 100%;
  background-size: cover; /* 保持比例，覆盖整个容器 */
  background-position: center; /* 图片居中显示 */
  background-repeat: no-repeat; /* 不重复显示 */
}

/* 上传图标居中显示，调整大小 */
.avatar-uploader-icon {
  font-size: 24px; /* 图标大小适中 */
  color: #8c8c8c; /* 图标颜色（灰色，符合默认风格） */
}
</style>


<script setup>
import {nextTick, onMounted, ref, toRaw} from "vue";
import api from "@/util/api.js";
import {Delete, Edit, PictureFilled, Plus, RefreshRight, Search, SoldOut} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {cloneDeep} from "lodash";
import {getJwt} from "@/api/jwt.js";
import {baseUrl} from "@/api/base.js";

//当组件挂载完毕之后触发
onMounted(async() => {
  await search();
})

//头像请求头
const headers = {
  Authorization: getJwt()
};

//数据模型
let venueModel = ref();

//搜索模型
let venueSearchModel = ref({
  code: "",
  name: "",
  type: "",
  status: "",
  openRange: ["", ""]
});

//分页模型
let customerPage = ref({
  pageNo: 1,
  pageSize: 10,
  total: 0
});

//表格行
let tableRows = ref();

//新增/修改场地模型
let venueFormModel = ref({
  code: "",
  name: "",
  type: "",
  capacity: "",
  status: "",
  openTime: "",
  closeTime: "",
  description: "",
  location: "",
  avatar: ""
})

//场地启用
function isNormal(status) {
  return status === "启用";
}

//场地禁用
function isDisable(status) {
  return status === "禁用";
}

//查询全部
async function search(pageNo, pageSize) {
  //查询条件
  let params = venueSearchModel.value;
  if (params.openRange) {
    params.startTime = params.openRange[0];
    params.endTime = params.openRange[1];
  }
  delete params.openRange;
  //console.log(params.startTime);
  //console.log(params.endTime);
  //console.log(params)
  let resp = await api({
    url: "/admin/venue",
    method: "get",
    params: {
      pageNo,
      pageSize,
      ...params
    },
  })
  venueModel.value = resp.data.records; //返回会员信息
  //console.log(resp.data.records);
  customerPage.value.pageNo = resp.data.current; //当前页码
  customerPage.value.pageSize = resp.data.size; //当前页大小
  customerPage.value.total = resp.data.total; //总记录数
  //console.log(customerPage.value)
}

//点击重置按钮时触发
function reset() {
  venueSearchModel.value = {
    code: "",
    name: "",
    type: "",
    status: "",
    openRange: ["", ""]
  }
  search();
}

//当页码或页面大小改变时触发
function changePage(pageNo, pageSize) {
  search(pageNo, pageSize);
}

//对话框显示状态
let showDialog = ref(false);
//对话框标题
let setTitle = ref("新增");
//进入对话框时触发
let dialogType = ref("add");

//提交对话框
function submitDialog() {
  if (dialogType.value === "add") {
    submitAdd();
  } else {
    submitUpdate();
  }
}

//点击新增按钮时触发
function add() {
  showDialog.value = true;
  setTitle.value = "新增";
  dialogType.value = "add";
  venueFormModel.value = {
    code: "",
    name: "",
    type: "",
    capacity: "",
    status: "",
    openTime: "",
    closeTime: "",
    description: "",
    location: "",
    avatar: ""
  }
}

//新增对话框中点击确认按钮时触发
async function submitAdd() {
  let params = toRaw(venueFormModel.value)
  //console.log(params);
  let resp = await api({
    url: "/admin/venue",
    method: "post",
    data: params
  })
  //console.log(resp);
  if (resp.success) {
    showDialog.value = false;
    ElMessage.success("新增成功");
    await search();
  } else {
    ElMessage.error("新增失败");
  }
}

//点击修改按钮时触发
function update(row) {
  //console.log(row);
  showDialog.value = true;
  setTitle.value = "修改";
  dialogType.value = "update";
  //在下一个时间滴答中操作
  nextTick(() => {
    //深度克隆
    venueFormModel.value = cloneDeep(toRaw(row))
    console.log(venueFormModel.value);
  })
}

//修改对话框中点击确认按钮时触发
async function submitUpdate() {
  let params = toRaw(venueFormModel.value)
  //console.log(params);
  let resp = await api({
    url: "/admin/venue",
    method: "put",
    data: params
  })
  console.log(resp);
  if (resp.success) {
    showDialog.value = false;
    ElMessage.success("修改成功");
    await search();
  } else {
    ElMessage.error("修改失败");
  }
}

//点击批量删除按钮时触发
function batchRemove() {
  let rows = tableRows.value.getSelectionRows();
  //console.log(rows.length);
  if (rows.length === 0) {
    ElMessage.warning("请选择要删除的行");
  } else {
    remove(rows);
  }
}

//点击删除按钮时触发
function remove(rows) {
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async() => {
    let ids = rows.map(item => item.id);
    console.log(ids);
    let resp = await api({
      url: "/admin/customer",
      method: "delete",
      data: ids
    })
    if (resp.success) {
      ElMessage.success("删除成功");
      await search();
    } else {
      ElMessage.error("删除失败");
    }
  }).catch(() => {
    ElMessage.info("已取消删除");
  })
}

//翻转行状态
async function toggleRowStatus(row) {
  let status = row.status;
  if (status === "启用") {
    row.status = "禁用";
  } else {
    row.status = "启用";
  }
  let resp = await api({
    url: "/admin/venue",
    method: "put",
    data: {
      id: row.id,
      status: row.status
    }
  })
  if (resp.success) {
    ElMessage.success("修改成功");
    await search();
  } else {
    ElMessage.error("修改失败");
  }
}

//获取行样式
function getRowClass({row}) {
  //console.log(row.status);
  if (row.status === "禁用") {
    return 'row-disable';
  } else {
    return '';
  }
}

//头像上传成功
function handleAvatarSuccess(resp) {
  venueFormModel.value.avatar = resp.data;
  //console.log("当前头像 URL:", venueFormModel.value.avatar); // 确认是否为正确的可访问 URL
}
</script>
